package com.dev.warehouse.bus.service.impl;

import com.dev.warehouse.bus.entity.Goods;
import com.dev.warehouse.sys.common.WebUtils;
import com.dev.warehouse.sys.entity.Loginfo;
import com.dev.warehouse.sys.entity.User;
import com.dev.warehouse.sys.service.ILoginfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 异步服务调用类
 * @author GuXiaoYao
 * @version 1.0.0
 * @since 2021/6/7
 */
@Service
public class AsynService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private ILoginfoService loginfoService;
    /**
     * 异步发送邮件提醒
     * @param user 当前登录用户
     * @param goodsName 商品名称
     * @param surplus 剩余商品数量
     */
    @Async
    public void sendTipsMessage(User user, String goodsName, int surplus) {
        //如果小于等于预警值的话，发送邮件提醒用户
        // 构建一个邮件对象
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件主题
        message.setSubject("商品数量已到达预警值");
        // 设置邮件发送者，这个跟application.yml中设置的要一致
        message.setFrom("cxy_xyj@126.com");
        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        message.setTo(user.getEmail());
        // 设置邮件发送日期
        message.setSentDate(new Date());
        // 设置邮件的正文
        message.setText(user.getName()+"您好，"+goodsName+"的数量已达到预警值，目前仅剩"+surplus+"(个)，请及时进货");
        // 发送邮件
        javaMailSender.send(message);
    }

    /**
     * 异步保存登录日志
     */
    @Async
    public void saveLoginInfo(User user, HttpServletRequest request){
        //记录登陆日志
        Loginfo entity = new Loginfo();
        entity.setLoginname(user.getName()+"-"+user.getLoginname());
        entity.setLoginip(request.getRemoteAddr());
        entity.setLogintime(new Date());
        loginfoService.save(entity);
    }


    /**
     * 获取登录用户的IP地址
     * @param request 请求request
     * @return 地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}
